<script setup>
	import MemberSelector from './memberSelector.vue'
	import { ref } from 'vue'
	import { message } from 'ant-design-vue'
	import { EditOutlined, DeleteOutlined, UserOutlined, TeamOutlined, ApartmentOutlined } from '@ant-design/icons-vue'
	import dashboardApi from '@/views/plugin/dashboard/api/dashboardApi'
	import { designStore } from '@/views/plugin/dashboard/store/design'
	const description = ref('')
	const dsConfigSource = ref()
	const chartName = ref('未命名图表')
	const shareLinkEnabled = ref(false)
	const permissionGroups = ref([
		// { name: '管理员组', view: true, move: true, copy: true, design: true, download: true, delete: true, members: [] },
		// {
		// 	name: '普通用户组',
		// 	view: true,
		// 	move: false,
		// 	copy: false,
		// 	design: false,
		// 	download: false,
		// 	delete: false,
		// 	members: []
		// }
	])
	const refreshInterval = ref(0)
	const open = ref(false)
	const permissionType = ref('1')
	const editName = ref(false)
	const groupIndex = ref(null)
	const id = ref('')
	const type = ref('')
	const categorizeId = ref('')
	const enabled = ref(1)

	const showDrawer = (item) => {
		if (item && item.id) {
			chartName.value = item.name
			description.value = item.description
			type.value = item.type
			categorizeId.value = item.categorizeId
			enabled.value = item.enabled
			const dsConfig = JSON.parse(item.dsConfig)
			dsConfigSource.value = dsConfig
			refreshInterval.value = dsConfig.refreshInterval
			shareLinkEnabled.value = dsConfig.shareLinkEnabled
			permissionType.value = dsConfig.permissionType
			permissionGroups.value = dsConfig.permissionGroups
			id.value = item.id
		} else {
			// 初始化表单数据
			chartName.value = '未命名图表'
			description.value = ''
			type.value = ''
			categorizeId.value = ''
			enabled.value = 1
			refreshInterval.value = 0
			shareLinkEnabled.value = false
			permissionType.value = '1'
			permissionGroups.value = []
			id.value = ''
		}
		open.value = true
	}

	const editGroup = (group, index) => {
		groupIndex.value = index
		editName.value = true
	}

	const deleteGroup = (group) => {
		permissionGroups.value = permissionGroups.value.filter((g) => g !== group)
	}

	// 成员选择器引用
	const memberSelectorRef = ref(null)

	// 打开成员选择器
	const addGroupMember = (group) => {
		memberSelectorRef.value.showModal(group)
	}

	const afterOpenChange = (bool) => {
		console.log('open', bool)
	}

	const decreaseRefreshInterval = () => {
		if (refreshInterval.value > 0) {
			refreshInterval.value--
		}
	}

	const increaseRefreshInterval = () => {
		refreshInterval.value++
	}

	const addPermissionGroup = () => {
		let count = 0
		if (permissionGroups.value?.length > 0) {
			count = permissionGroups.value.filter((e) => e.name.includes('新权限组')).length
		} else {
			permissionGroups.value = []
		}
		console.log(count)
		permissionGroups.value.push({
			name: `新权限组${count >= 1 ? count + 1 : '1'}`,
			view: false,
			move: false,
			copy: false,
			design: false,
			download: false,
			delete: false,
			members: []
		})
	}

	const save = (type) => {
		editName.value = false
	}

	const cancel = (type) => {
		editName.value = false
	}

	const handleSave = async () => {
		try {
			const params = {
				id: id.value,
				name: chartName.value,
				description: description.value,
				type: type.value,
				categorizeId: designStore().currentCategoryId,
				enabled: enabled.value,
				dsConfig: JSON.stringify({
					...dsConfigSource.value,
					refreshInterval: refreshInterval.value,
					shareLinkEnabled: shareLinkEnabled.value,
					permissionType: permissionType.value,
					permissionGroups: permissionGroups.value
				})
			}
			await dashboardApi.dashboardListEdit(params)
			await designStore().fetchDashboardList()
			open.value = false
		} catch (error) {
			console.error('保存设置失败:', error)
		}
	}

	const handleCancel = () => {
		open.value = false
	}

	defineExpose({ showDrawer })
</script>

<template>
	<a-drawer
		v-model:open="open"
		class="custom-class"
		root-class-name="root-class-name"
		title="设置"
		placement="right"
		@after-open-change="afterOpenChange"
		width="1000"
	>
		<div>
			<h3 style="font-weight: bold">页面设置</h3>
			<div class="mt-5">
				<label for="chartName" class="block mb-2">图表名称</label>
				<a-input
					id="chartName"
					v-model:value="chartName"
					type="text"
					class="border border-gray-300 rounded-md p-2 w-full"
					placeholder="未命名图表"
				/>
			</div>
			<div class="mt-5">
				<label for="description" class="block mb-2">描述</label>
				<a-textarea
					id="description"
					v-model:value="description"
					class="border border-gray-300 rounded-md p-2 w-full"
					:rows="4"
					placeholder="没有添加描述"
				></a-textarea>
			</div>
			<div class="mt-5">
				<label for="refreshInterval" class="block mb-2">定时刷新间隔(s)</label>
				<div class="flex items-center">
					<a-input
						id="refreshInterval"
						v-model:value="refreshInterval"
						type="number"
						class="border border-gray-300 rounded-md p-2 w-full"
						min="10"
					/>
				</div>
			</div>
			<div class="mt-5">
				<label for="shareLink" class="block mb-2">开启分享链接(用于第三方嵌入页面使用)</label>
				<a-switch v-model:checked="shareLinkEnabled"></a-switch>
			</div>

			<!-- 新增权限设置部分 -->
			<div class="mt-5">
				<h3 style="font-weight: bold">权限设置</h3>
				<p>根据实际业务场景，权限设置看灵活配置用户、角色、部门操作权限。</p>
				<div class="mt-5">
					<a-radio-group v-model:value="permissionType" name="radioGroup">
						<a-radio value="1">公开权限（所有功能都可使用）</a-radio>
						<a-radio value="2">自定义权限</a-radio>
					</a-radio-group>
				</div>
				<div class="mt-5" v-if="permissionType === '2'">
					<a-button type="primary" @click="addPermissionGroup">添加权限组</a-button>
				</div>

				<!-- 权限组内容 -->
				<template v-if="permissionType === '2'">
					<div v-for="(group, index) in permissionGroups" :key="index" class="mt-5 permission">
						<div class="bg-[#f5f6f7] p-[10px] rounded-t-[10px]">
							<div v-if="editName && groupIndex === index" class="flex justify-between items-center">
								<div>
									<span>权限组名称</span>
									<a-input v-model:value="group.name" class="w-[200px] ml-2" />
								</div>
								<div>
									<a-button type="primary" @click="save(group)">保存</a-button>
									<a-button @click="cancel(group)" class="ml-2">取消</a-button>
								</div>
							</div>
							<div v-else class="flex justify-between items-center">
								<span>{{ group.name }}</span>
								<div>
									<a-button type="link" @click="editGroup(group, index)">
										<template #icon>
											<EditOutlined />
										</template>
										编辑
									</a-button>
									<a-button type="link" danger @click="deleteGroup(group)">
										<template #icon>
											<DeleteOutlined />
										</template>
										删除
									</a-button>
								</div>
							</div>
						</div>
						<div class="p-[10px]">
							<a-row class="mt-5 flex items-center">
								<a-col :span="2">成员</a-col>
								<a-col :span="22">
									<div>
										<a-button type="link" @click="addGroupMember(group)">+添加成员/角色/部门</a-button>
										<div v-if="group.members && group.members.length > 0" class="mt-2">
											<a-tag v-for="member in group.members" :key="member.type + '-' + member.id" class="mb-1">
												<UserOutlined v-if="member.type === 'user'" />
												<TeamOutlined v-if="member.type === 'role'" />
												<ApartmentOutlined v-if="member.type === 'dept'" />
												<span class="ml-1">{{ member.name }}</span>
											</a-tag>
										</div>
									</div>
								</a-col>
							</a-row>
							<a-row class="mt-5 flex items-center">
								<a-col :span="2">操作权限</a-col>
								<a-col :span="22">
									<div class="flex gap-4">
										<a-checkbox v-model:checked="group.view">查看</a-checkbox>
										<!--									<a-checkbox v-model:checked="group.move">移动</a-checkbox>-->
										<!--									<a-checkbox v-model:checked="group.copy">复制</a-checkbox>-->
										<a-checkbox v-model:checked="group.design">设计</a-checkbox>
										<!--									<a-checkbox v-model:checked="group.download">下载</a-checkbox>-->
										<!--									<a-checkbox v-model:checked="group.delete">删除</a-checkbox>-->
									</div>
								</a-col>
							</a-row>
						</div>
					</div>
				</template>
			</div>
		</div>
		<template #footer>
			<div style="text-align: right">
				<a-button style="margin-right: 8px" @click="handleCancel">取消</a-button>
				<a-button type="primary" @click="handleSave">保存设置</a-button>
			</div>
		</template>
	</a-drawer>

	<!-- 成员选择器组件 -->
	<member-selector ref="memberSelectorRef" />
</template>

<style scoped lang="less">
	.permission {
		border: 1px solid #1e6fff;
		border-radius: 2px;
	}
</style>
